package sddz.foodmanage.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.foamtrace.photopicker.PhotoPickerActivity;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.adapter.RecyclerAdapter;
import sddz.foodmanage.adapter.UniversalAdapter;
import sddz.foodmanage.adapter.UniversalViewHolder;
import sddz.foodmanage.adapter.ViewHolder;
import sddz.foodmanage.base.BaseActivity;
import sddz.foodmanage.dialog.PhotoDialog;
import sddz.foodmanage.model.WaitListBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.SpfUtils;
import sddz.foodmanage.view.MyListView;

import static sddz.foodmanage.dialog.PhotoDialog.PICK_FROM_CAMERA;
import static sddz.foodmanage.dialog.PhotoDialog.SELECT_PHOTO;

/**
 * @Date:2019/7/10
 * @Author:lbb 待评论详情页面, 待配送同样复用
 */
public class WaitCommentActivity extends BaseActivity {


    @BindView(R.id.title_navigation_icon)
    ImageView titleNavigationIcon;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.title_menu_icon)
    ImageView titleMenuIcon;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.image_title_right)
    ImageView imageTitleRight;
    @BindView(R.id.title_layout)
    AppBarLayout titleLayout;
    @BindView(R.id.tv_pingji)
    TextView tvPingji;
    @BindView(R.id.tv_zhongdui)
    TextView tvZhongdui;
    @BindView(R.id.lv_order)
    MyListView lvOrder;
    @BindView(R.id.tv_you)
    TextView tvYou;
    @BindView(R.id.tv_liang)
    TextView tvLiang;
    @BindView(R.id.tv_zhong)
    TextView tvZhong;
    @BindView(R.id.tv_cha)
    TextView tvCha;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.send_gather_rv)
    RecyclerView sendGatherRv;
    @BindView(R.id.all_image)
    AutoLinearLayout allImage;
    @BindView(R.id.image_add)
    ImageView imageAdd;
    @BindView(R.id.all_waitcomment)
    AutoLinearLayout allWaitcomment;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.tv_dinner_num)
    TextView tvDinnerNum;//用餐人数
    @BindView(R.id.activity_wait_comment)
    AutoLinearLayout activityWaitComment;
    private PhotoDialog photoDialog;
    private List<WaitListBean.DataBean.GoodsBean> goodslist = new ArrayList<>();
    private UniversalAdapter<WaitListBean.DataBean.GoodsBean> adapter;
    private ArrayList<String> mList = new ArrayList<>();//图片
    private RecyclerAdapter<String> mAdapter;
    private String imagePath;
    private String status;
    WaitListBean.DataBean DataBeanps;
    WaitListBean.DataBean DataBeanpl;
    String gradecode = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wait_comment);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        adapter = new UniversalAdapter<WaitListBean.DataBean.GoodsBean>(mActivity, goodslist, R.layout.item_row_list) {
            @Override
            public void convert(UniversalViewHolder holder, int position, WaitListBean.DataBean.GoodsBean goodsBean) {
                if (status.equals("待配送")) {
                    holder.getView(R.id.tv_sjweight).setVisibility(View.GONE);
                } else {
                    holder.getView(R.id.tv_sjweight).setVisibility(View.VISIBLE);
                }
                holder.setText(R.id.tv_name, goodsBean.getName());
                holder.setText(R.id.tv_unit, goodsBean.getPrice() + "元/" + goodsBean.getUnit());
                holder.setText(R.id.tv_xdweight, goodsBean.getAmount_data() + goodsBean.getUnit());//getAmount最新数量
                holder.setText(R.id.tv_sjweight, goodsBean.getAmount() + goodsBean.getUnit());//getAmount_data下单时的数量
                holder.setText(R.id.tv_zongje, goodsBean.getTotal_price() + "元");
                //==================================================================================
                //判断有没有备注信息 如果有显示黑色的图标 如果没有显示灰色的图标
                final String remark = goodsBean.getRemark();
                if (remark.isEmpty()) {
                    holder.setImageResource(R.id.iv_note, R.mipmap.icon_remark_gray);
                } else {
                    holder.setImageResource(R.id.iv_note, R.mipmap.icon_remark_red);
                }
                holder.getView(R.id.iv_note).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //打开备注信息 如果有的话
                        if (!remark.isEmpty()) {
                            final EditText editText = new EditText(WaitCommentActivity.this);
                            editText.setFocusable(false);
                            editText.setText(remark);
                            AlertDialog.Builder inputDialog =
                                    new AlertDialog.Builder(WaitCommentActivity.this);
                            inputDialog.setTitle("备注信息:").setView(editText)
                                    .setPositiveButton("关闭",
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                }
                                            }).show();

                        }
                    }
                });
                //==================================================================================
            }

        };
        lvOrder.setAdapter(adapter);
        //拍照
        photoDialog.setOnChoosePhotoListener(new PhotoDialog.OnChoosePhotoListener() {
            @Override
            public void openAlbum() {
                photoDialog.openAlbum(3 - mList.size());
            }

            @Override
            public void openCamera() {
                if (mList.size() < 3) {
                    photoDialog.openCamera();
                } else {
                    show("图片已达到上限");
                }

            }
        });
    }


    private void initData() {
        Intent intent = getIntent();

        status = intent.getStringExtra("status");

        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        if (!TextUtils.isEmpty("status") && status.equals("待评论")) {//编辑页面
            titleText.setText("待评论");
//            tvHuitui.setVisibility(View.GONE);
            DataBeanpl = (WaitListBean.DataBean) intent.getSerializableExtra("data");
            goodslist.addAll(DataBeanpl.getGoods());
            tvZhongdui.setText(DataBeanpl.getTotal_price() + "元");
            tvPingji.setText(DataBeanpl.getNumber() + "");
            tvDinnerNum.setText(DataBeanpl.getDinner_num()+"");
        } else if (!TextUtils.isEmpty("status") && status.equals("订单详情")) {
            titleText.setText("订单详情");
            tvYou.setSelected(false);
            tvLiang.setSelected(false);
            tvZhong.setSelected(false);
            tvCha.setSelected(false);
            etContent.setSelected(false);
            etContent.clearFocus();
            tvComment.setVisibility(View.GONE);
//            tvHuitui.setVisibility(View.GONE);
        } else if (!TextUtils.isEmpty("status") && status.equals("待配送")) {
            titleText.setText("待配送");
            tvComment.setText("配送");
            DataBeanps = (WaitListBean.DataBean) intent.getSerializableExtra("data");
            goodslist.addAll(DataBeanps.getGoods());
            tvZhongdui.setText(DataBeanps.getTotal_price() + "元");
            tvPingji.setText(DataBeanps.getNumber() + "");
            allWaitcomment.setVisibility(View.GONE);
            tvDinnerNum.setText(DataBeanps.getDinner_num()+"");
//            tvHuitui.setVisibility(View.VISIBLE);
        }
    }

    private void initView() {
        titleText.setText("待评论");
        photoDialog = new PhotoDialog(mActivity);
        mAdapter = new RecyclerAdapter<String>(mActivity, mList, R.layout.image_item_layout) {
            @Override
            protected void convert(ViewHolder holder, String s, final int position) {
                for (int aa = 0; aa < mList.size(); aa++) {
                    if (!s.contains("http:")) {
                        holder.setImageFile(mActivity, R.id.iv_item, s);
                    } else {
                        holder.setImageFile2(mActivity, R.id.iv_item, s);
                    }
                }

                if (mList.size() == 3) {
                    imageAdd.setVisibility(View.GONE);
                } else {
                    imageAdd.setVisibility(View.VISIBLE);
                }
                holder.getView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mList.remove(position);
                        if (mList.size() == 0) {
                            sendGatherRv.setVisibility(View.GONE);
                            allImage.setVisibility(View.GONE);
                        } else {
                            sendGatherRv.setVisibility(View.VISIBLE);
                            allImage.setVisibility(View.VISIBLE);
                        }
                        if (mList.size() == 3) {
                            imageAdd.setVisibility(View.GONE);
                        } else {
                            imageAdd.setVisibility(View.VISIBLE);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                });

            }
        };
        sendGatherRv.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        sendGatherRv.setAdapter(mAdapter);
    }

    @OnClick({R.id.title_navigation_icon, R.id.tv_you, R.id.tv_comment, R.id.tv_liang, R.id.tv_zhong,
            R.id.tv_cha, R.id.image_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_navigation_icon:
                finish();
                break;
            case R.id.tv_you:
                tvYou.setBackgroundDrawable(getResources().getDrawable(R.drawable.redcircle));
                tvLiang.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
                tvZhong.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
                tvCha.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
//                tvYou.setBackground(getDrawable(R.drawable.redcircle));
//                tvLiang.setBackground(getDrawable(R.drawable.graycircle));
//                tvZhong.setBackground(getDrawable(R.drawable.graycircle));
//                tvCha.setBackground(getDrawable(R.drawable.graycircle));
                gradecode = "1";
                break;
            case R.id.tv_liang:
                tvYou.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
                tvLiang.setBackgroundDrawable(getResources().getDrawable(R.drawable.redcircle));
                tvZhong.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
                tvCha.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
//                tvLiang.setBackground(getDrawable(R.drawable.redcircle));
//                tvZhong.setBackground(getDrawable(R.drawable.graycircle));
//                tvCha.setBackground(getDrawable(R.drawable.graycircle));
                gradecode = "2";
                break;
            case R.id.tv_zhong:
//                tvYou.setBackground(getDrawable(R.drawable.graycircle));
//                tvLiang.setBackground(getDrawable(R.drawable.graycircle));
//                tvZhong.setBackground(getDrawable(R.drawable.redcircle));
//                tvCha.setBackground(getDrawable(R.drawable.graycircle));
                tvYou.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
                tvLiang.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
                tvZhong.setBackgroundDrawable(getResources().getDrawable(R.drawable.redcircle));
                tvCha.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
                gradecode = "3";
                break;
            case R.id.tv_cha:
//                tvYou.setBackground(getDrawable(R.drawable.graycircle));
//                tvLiang.setBackground(getDrawable(R.drawable.graycircle));
//                tvZhong.setBackground(getDrawable(R.drawable.graycircle));
//                tvCha.setBackground(getDrawable(R.drawable.redcircle));
                tvYou.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
                tvLiang.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
                tvZhong.setBackgroundDrawable(getResources().getDrawable(R.drawable.graycircle));
                tvCha.setBackgroundDrawable(getResources().getDrawable(R.drawable.redcircle));
                gradecode = "4";
                break;
            case R.id.image_add://添加图片
                photoDialog.showDialog(view);
                break;
            case R.id.tv_comment:
                if (tvComment.getText().equals("配送")) {
                    peisong();
                } else if (tvComment.getText().equals("评论")) {
                    pinglun();
                }
                break;
//            case R.id.tv_huitui://回退
//
//                break;
        }
    }

    /**
     * 评论
     */
    private void pinglun() {
        dialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("id", DataBeanpl.getId());
        map.put("grade", gradecode);
        map.put("comment", etContent.getText().toString());
        JSONObject object = new JSONObject(map);
        Log.e("评论数据", object.toString());
        for (int a = 0; a < mList.size(); a++) {
            Log.e("mList", mList.size() + "" + mList.get(a).toString());
        }
        HttpUtils.getInstance().UpFile(mActivity, API.getcomments, mList, object.toString(), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(final String body) {
                dialog.dismiss();
                Log.e("评论返回结果", body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");

                        if (code == 200) {
                            if (!jsonObject.optString("message").equals("")) {
                                show(jsonObject.optString("message"));
                            }
                            finish();
                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            pinglun();
                        } else if (code == 401) {
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Request error, Exception e) {
                dialog.dismiss();
                show("提交失败，请稍后重试");
            }
        });
    }

    /**
     * 配送
     */
    private void peisong() {
        Map<String, String> map = new HashMap<>();
        map.put("id", DataBeanps.getId() + "");
        dialog.show();
        HttpUtils.getInstance().POST(mActivity, API.getsubmitpeisong, JSON.toJSONString(map), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                dialog.dismiss();
                Log.e("配送返回的数据", body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
                        if (!jsonObject.optString("message").equals("")) {
                            show(jsonObject.optString("message"));
                        }
                        if (code == 200) {
                            finish();
                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            Log.e("33333333", token);
                            SpfUtils.savetoken(mActivity, token);
                            peisong();
                        } else if (code == 401) {
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Request error, Exception e) {
                dialog.dismiss();

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //获取相册的照片
                case SELECT_PHOTO:
                    ArrayList<String> list = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    mList.addAll(list);
//                    for (int q = 0; q < mList.size(); q++) {
//                        Log.e("mListqqqqqqqqqqqqqqqq", mList.get(q).toString());
//                    }
                    sendGatherRv.setVisibility(View.VISIBLE);
                    allImage.setVisibility(View.VISIBLE);
                    if (mList.size() == 3) {
                        imageAdd.setVisibility(View.GONE);
                    } else {
                        imageAdd.setVisibility(View.VISIBLE);
                    }
                    mAdapter.notifyDataSetChanged();
                    break;
                //获取拍摄的照片
                case PICK_FROM_CAMERA:
                    imagePath = photoDialog.getImagePath();
                    if (!TextUtils.isEmpty(imagePath) && mList.size() < 3) {
                        mList.add(imagePath);
                    }
                    sendGatherRv.setVisibility(View.VISIBLE);
                    allImage.setVisibility(View.VISIBLE);
                    if (mList.size() == 3) {
                        imageAdd.setVisibility(View.GONE);
                    } else {
                        imageAdd.setVisibility(View.VISIBLE);
                    }
                    mAdapter.notifyDataSetChanged();
                    break;

            }
        }
    }

}
